import pyciv.action
import pyciv.attribute
import pyciv.terrain

class Unit(object):
    def __init__(self, name, attributes = {}):
        self.name = name
        self.attributes = attributes
        self.attributes[pyciv.attribute.ACTIONPOINTS] = 0
        self.attributes[pyciv.attribute.DEFENCE] = 0
        
    def strength(self):
        result = 0
        for key, value in self.attributes.iteritems():
            result += key.count(value)
        return result

    def supply_needed_to_move(self):
        result = 0
        for key, value in self.attributes.iteritems():
            result += key.supply_needed_to_move(value)
        return result

    def alive(self):
        return self.strength() > 0

    def ready_for_action(self):
        return self.attributes[pyciv.attribute.ACTIONPOINTS] > 0

    def create_targets(self, defender):
        targets = []
        for key, value in self.attributes.iteritems():
            targets.extend(key.create_targets(value, defender))
        return targets

    def prepare_turn(self):
        self.attributes[pyciv.attribute.ACTIONPOINTS] = \
            self.attributes[pyciv.attribute.MOBILITY] * 2

    def __str__(self):
        result = ""
        for key, value in self.attributes.iteritems():
            result += "%s%d" % (str(key)[0], value)
        return result

    def _move_or_switch(self, hex, engine):
        if engine.state.unit[hex] == pyciv.unit.NONE:
            return pyciv.action.Move(hex, engine)
        else:
            if engine.state.owner[hex] != engine.current_player():
                return pyciv.action.Attack(hex, engine)
            else:
                return pyciv.action.Switch(hex, engine)

    def generate_hex_action(self, hex, engine):
        if self.ready_for_action() and not hex == engine.current_hex:
            if engine.next_to_current_hex(hex):
                return self._move_or_switch(hex, engine)
        return pyciv.action.NONE
    
    def generate_actions(self, current_hex, engine):
        if self.ready_for_action():
            return [pyciv.action.Defend(current_hex, engine),
                    pyciv.action.Reserve(current_hex, engine, pyciv.attribute.FIREPOWER),
                    pyciv.action.Reserve(current_hex, engine, pyciv.attribute.PROTECTION),
                    pyciv.action.Reserve(current_hex, engine, pyciv.attribute.MOBILITY)]
        else:
            return []

class Empty(Unit):
    def __init__(self):
        Unit.__init__(self, "")

    def prepare_turn(self):
        pass

    def generate_hex_action(self, hex, engine):
        return pyciv.action.NONE
    
    def generate_actions(self, current_hex, engine):
        actions = []
        return actions

    def __str__(self):
        return ""

NONE = Empty()
